package com.hongxun.design.activitys;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentActivity;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyAPPActivity;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.bean.ConsumerInfo;
import com.hongxun.design.bean.ProjectItemBean;
import com.hongxun.design.interfaces.MessageInterface;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.utils.StringUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.soundUtil.UPlayer;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.UTrack;

import java.util.List;

import static com.hongxun.design.MyApp.activity;
import static com.hongxun.design.utils.fastjson.FastJsonUtil.JsonToLoginData;

/**
 * Created by zerdoor_pc on 2016/4/25.
 * 基础Activity
 */
public class BaseActivity extends FragmentActivity implements MessageInterface {
    protected FragmentActivity mActivity;
    protected String TAG;
    BaseActivity baseActivity;
    boolean isAppBack = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉上方bar
        isAppBack = false;
        addConerHandler();
        MyAPPActivity.getInstance().addActivity(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止横屏
        MobclickAgent.setCatchUncaughtExceptions(true);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("userInfo", JSON.toJSONString(MyApp.userInfo));
        outState.putString("projectInfo", JSON.toJSONString(MyApp.currProject));
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        activity = this;
        mActivity = this;
        TAG = MyApp.AppName + ":  " + this.getClass().getSimpleName();
        MyApp.HTTP.http.isLoad = true;
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        activity = this;
        mActivity = this;
        baseActivity = this;
        MobclickAgent.onResume(this);

        if (MyApp.NetWorkConnect && MyApp.isOnLine && isAppBack &&
                isAppOnForeground() && MyApp.userInfo != null &&
                !StringUtil.isEmpty(MyApp.userInfo.getOpenIdent())) {
            isAppBack = false;
            MyApp.HTTP.ConsumerInfo(onlineCheckHandler, HttpStringUtil.SUCCESSED);
        }
    }

    private Handler onlineCheckHandler;

    private void addConerHandler() {
        onlineCheckHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            ConsumerInfo info = JsonToLoginData((String) msg.obj);
                            if (info != null && info.getOrg_id().equalsIgnoreCase(MyApp.userInfo.getOrg_id())) {
                            } else {
                                ToastShow.showShort(activity, "用户单位已变化,请重新登录");
                                try {
                                    MyApp.mPushAgent.removeAlias(MyApp.userInfo.getUser_id(), MyApp.PushType,
                                            new UTrack.ICallBack() {
                                                @Override
                                                public void onMessage(boolean isSuccess, String message) {
                                                }
                                            });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                MyApp.userInfo.clearBean();//清理个人信息
                                MyApp.currProject.clearBean();//清理项目
                                MyApp.ISOUTLOGIN = true;
                                MyApp.iscreate = true;
                                if (MyApp.HomeActivity != null) MyApp.HomeActivity.closeService();
                                IntentToActivity.intent(activity, LoginActivity.class);
                                activity.finish();
                            }
                        } else {
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                }
            }
        };
    }


    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        isAppBack = true;
    }

    /**
     * 初始化控件并进行基础设置*
     */
    protected void findView() {

    }

    /**
     * 初始化数据及控件*
     */
    protected void initialization() {

    }

    /**
     * 加载更多代码*
     */
    public void addMore() {

    }

    @Override
    public void onBackPressed() {
        try {

            UPlayer.back();
        } catch (Exception e) {
        }
        super.onBackPressed();

    }

    public void RefreshData() {

    }

    /**
     * 判断app是否在前台*
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device
        try {
            ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
            String packageName = getApplicationContext().getPackageName();

            List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                    .getRunningAppProcesses();
            if (appProcesses == null)
                return false;

            for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
                // The name of the process that this object is associated with.
                if (appProcess.processName.equals(packageName)
                        && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }

    }

    @Override
    public void Nofity() {

    }


    /******
     * 显示等待框*
     *
     * @param layoutId 要显示的 layout 文件, <1 则用默认的
     **/
    public static Dialog showWaitDialog(final int layoutId, final String... text) {
        if (MyApp.activity == null)
            return null;
        try {
            showWaitIngDialog = true;
            (new Handler()).post(new Runnable() {
                @Override
                public void run() {
                    if (!showWaitIngDialog) return;
                    if (dialog != null) {
                        hideWaitIngDialog();
                    }

                    try {
                        if (dialog != null) dialog = null;
                        dialog = new Dialog(MyApp.activity, R.style.dialog_nodimamount);
                        dialog.setCancelable(true);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setContentView(layoutId < 1 ? R.layout.dialog_wait_holo : layoutId);
                        if (layoutId == -1) {
                            ImageView image_progress = (ImageView) dialog.findViewById(R.id.image_progress);
                            image_progress.setImageResource(R.drawable.anim_loading);
                            AnimationDrawable animationDrawable = (AnimationDrawable) image_progress.getDrawable();
                            animationDrawable.start();
                            if (text != null && text.length > 0) {
                                ((TextView) dialog.findViewById(R.id.textView)).setText(text[0]);
                            }
                        }
                        MyLog.L("showWaitDialog" + dialog);
                        dialog.show();
                    } catch (Exception e) {
                        MyLog.L(e.getMessage());
                    }
                }
            });

        } catch (Exception e) {
            // LogTool.ex(e);
        }
        return dialog;
    }

    static boolean showWaitIngDialog = false;

    /******
     * 隐藏等待框
     ***/
    public static void hideWaitIngDialog() {
        if (MyApp.activity == null)
            return;
        showWaitIngDialog = false;
        try {
            if (dialog != null) {
                dialog.dismiss();
            }
        } catch (Exception e) {
            MyLog.L(e.getMessage());
        }
    }

    static Dialog dialog;

    @SuppressLint("NewApi")
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            try {
                if (MyApp.userInfo == null) MyApp.userInfo = new ConsumerInfo();
                ConsumerInfo info = FastJsonUtil.JsonToLoginData(savedInstanceState.getString("userInfo", ""));
                if (info != null) MyApp.userInfo.setBean(info);
                if (MyApp.currProject == null) MyApp.currProject = new ProjectItemBean();
                ProjectItemBean pro = FastJsonUtil.JsonToGetProject(savedInstanceState.getString("projectInfo", ""));
                if (pro != null) MyApp.currProject.setBean(pro);
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        try {
            outState.putString("userInfo", JSON.toJSONString(MyApp.userInfo));
            outState.putString("projectInfo", JSON.toJSONString(MyApp.currProject));
        } catch (Exception e) {
        }
        super.onSaveInstanceState(outState, outPersistentState);
    }
}
